package com.shambles.manage2.utils;

import cn.hutool.core.date.DateUtil;
import org.junit.Test;

import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @author lz
 * @description 时间工具类
 * @date 2019/6/6
 */
public class TimeUtils extends DateUtil {
    public final static String exp2 = "yyyy-MM-dd HH:mm:ss";
    public final static long oneDayMillis = 24 * 60 * 60 * 1000;
    public final static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    public static String formatTime(long time, String pattern) {
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        return sdf.format(time);
    }

    /**
     * @Author lz
     * @Description: 获取两个时间之间的月数, 格式是时间戳
     * @param: [beginDate, endDate]
     * @Date: 2019/7/10 15:52
     **/
    public static Integer getMonths(Long beginDate, Long endDate) {
        if (endDate < beginDate) {
            return -1;
        }
        //SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c1 = Calendar.getInstance();
        Calendar c2 = Calendar.getInstance();
        c1.setTime(new Date(beginDate));
        c2.setTime(new Date(endDate));
        int year = c2.get(Calendar.YEAR) - c1.get(Calendar.YEAR);
        //开始日期若小于结束日期
        return year * 12 + c2.get(Calendar.MONTH) - c1.get(Calendar.MONTH);
    }

    public static long getDay0() {
        Calendar cal = Calendar.getInstance();
        cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
        return cal.getTimeInMillis();
    }

    public static long getMoth0() {
        Calendar cal = Calendar.getInstance();
        cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), 1, 0, 0, 0);
        return cal.getTimeInMillis();
    }

    public static List<String> getDayList(long sTime, long eTime) {
        List<String> dayList = new ArrayList<>();
        while (sTime < eTime) {
            dayList.add(formatter.format(LocalDateTime.ofInstant(Instant.ofEpochMilli(sTime), ZoneId.systemDefault())));
            sTime += oneDayMillis;
        }
        return dayList;
    }

    @Test
    public void test() {
        System.out.println(getMoth0());
    }
}
